// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()

// 云函数入口函数
exports.main = async(event, context) => {
  //获取word
  const word_id = event.word_id
  let res = await db.collection('word').where({
    word_id: word_id
  }).get();
  const word = res.data[0]

  //确定问题是假名还是意思
  var question = ''
  var key = ''
  var mode = -1 //0表示问题是假名答案是意思，1表示问题是意思答案是假名
  if (Math.random() < 0.5) {
    //问题是假名
    question = word.pronunciation
    key = word.meaning
    mode = 0
  } else {
    question = word.meaning
    key = word.pronunciation
    mode = 1
  }

  //获取options
  const options = []
  options.push(key)
  var already = new Array();
  already.push(event.word_id);
  for (let i = 0; i < 3; i++) {
    var random = 0;
    while (true) { //防止可能的重复
      random = parseInt((Math.random() * 3836 + 1).toFixed(0));
      if (!already.includes(random)) {
        //若already里面没有random则退出循环
        already.push(random);
        break;
      }
    }
    let randRes = await db.collection('word').where({
      word_id: random
    }).get();
    if (mode == 0) {
      options.push(randRes.data[0].meaning)
    } else if (mode == 1) {
      options.push(randRes.data[0].pronunciation)
    }
  }

  //随机排序
  for (var i = 0, len = options.length; i < len; i++) {
    var rand = parseInt(Math.random() * len);
    var temp = options[rand];
    options[rand] = options[i];
    options[i] = temp;
  }

  return {
    word: word,
    question: question,
    key: key,
    options: options
  }
}